package com.xueqiu.lovepetmedicalmanagersystem.controller;

import com.xueqiu.lovepetmedicalmanagersystem.pojo.Employee;
import com.xueqiu.lovepetmedicalmanagersystem.service.EmployeeService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xueqiu
 */
@Controller//放容器里的注解
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 跳转控制器；跳转到登陆页面
     * @return 登陆页面URL
     */
    //请求的地址与该方法之间的映射关系，用@RequestMapping这个注解
    @RequestMapping("/toLogin")
    public String toLogin(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().invalidate();
        //return日容是要跳转的视图URL
        return "login";
    }

    /**
     * 员工登录，同时也有名下宠物查询功能
     * @param username 员工用户名
     * @param password 密码
     * @param model 模型参数
     * @param request 请求参数
     * @param response 响应参数
     * @return 登陆成功则跳转到宠物搜索页面；登陆失败则跳转到登陆页面
     */
    @RequestMapping("/toPetSearch")
    public String sucLogin(
            @Param("name")
            String username,
            @Param("password")
            String password,
            Model model,
            HttpServletRequest request,
            HttpServletResponse response
    ) {

        Employee employee = employeeService.queryEmployeeByNameAndPwd(username, password);

        if (employee != null) {
            request.getSession().setAttribute("username", employee.getName());
            model.addAttribute("employee", employee);
            return "pet/petsearch";
        } else {
            model.addAttribute("msg", "登录失败，用户名密码错误！！！");
            return "login";
        }
    }
}
